'''
Created on 31.05.2011

@author: blaze
'''
# For Google Code Hosting.
import gdata.projecthosting.client
import ConfigParser

from t2g.utils.logger import logger

from t2g.reader.trac.db.sqlitereader import DataReader as Reader
from t2g.writer.gch.api.GCHWriter import GCHWriter as Writer
from t2g.utils import tips

def authenticate_client(client, project, username, password):
    """Authenticate CLIENT to PROJECT, with USERNAME and PASSWORD."""    
    client.client_login(username, password, source=project, service='code')
    

if __name__ == "__main__":
    
    logger.info("Start migration process from Trac to GCH")

    # Load migration settings from configuration file
    config = ConfigParser.ConfigParser()
    config.readfp(open('migration.cfg'))

    dbLocation = config.get('migration', 'source')
    gchUser = config.get('migration', 'gchUser')
    gchPassword = config.get('migration', 'gchPassword')
    gchProject = config.get('migration', 'gchProject')    
    defaulIssueOwner = config.get('migration', 'defaulIssueOwner')
    
    usermap = tips.tuplelist2dict(config.items('usermap'))
    
    # Initialize GCH client
    client = gdata.projecthosting.client.ProjectHostingClient()    
    authenticate_client(client, gchProject, gchUser, gchPassword)

    # Perform migration
    reader = Reader(dbLocation)
    writer = Writer(gchProject, client, gchUser, defaulIssueOwner)
    writer.setUserMap(usermap)
    
    tickets = reader.readTickets()
    
    for ticket in tickets.getTickets():        
        writer.import_issue(ticket)